﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace Happy.ExtentionMethods.Reflection
{
    /// <summary>
    /// 扩展<see cref="ICustomAttributeProvider"/>。
    /// </summary>
    public static class CustomAttributeProviderExtensions
    {
        /// <summary>
        /// 返回<paramref name="provider"/>上定义的第一个<typeparamref name="TAttribute"/>属性。
        /// </summary>
        public static TAttribute GetAttribute<TAttribute>(
            this ICustomAttributeProvider provider,
            bool inherit = true)
            where TAttribute : Attribute
        {
            provider.MustNotNull("provider");

            return
                    provider.IsDefined(typeof(TAttribute), inherit)
                    ? provider.GetAttributes<TAttribute>(inherit)[0]
                    : default(TAttribute);
        }

        /// <summary>
        /// 返回<paramref name="provider"/>上定义的<typeparamref name="TAttribute"/>数组，如果没有定义就返回空数组。
        /// </summary>
        public static TAttribute[] GetAttributes<TAttribute>(
            this ICustomAttributeProvider provider,
            bool inherit = true)
            where TAttribute : Attribute
        {
            provider.MustNotNull("provider");

            return
                    provider
                    .GetCustomAttributes(typeof(TAttribute), inherit)
                    .Cast<TAttribute>()
                    .ToArray();
        }
    }
}
